#!/usr/bin/python3
import os
from .Entity import Entity
from .Dictionary import Dictionary_Type
from utils import My_Util2


class DictionaryConstant:
    """
    数据字典类
    """

    def __init__(self, context, entity: Entity, dictionaries: list[Dictionary_Type]) -> None:
        self.context = context
        self.entity: Entity = entity
        self.lookups: list[Dictionary_Type] = dictionaries
        self.my_util2 = My_Util2.My_Util(self.context)

    def code_dictionary(self):
        lookups = list[str]()
        for lookup_type in self.lookups:
            for item in lookup_type.lookup_items:
                code = item.code
                field_name = code.replace(":", "_")
                lookups.append(
                    f"""
    /**
     * {lookup_type.description}：{item.description}
     */
    String {field_name} = "{code}";
    {field_name}({code}, {field_name}),
"""
                )
        return "\n".join(lookups)

    def code(self):
        author = self.entity.author
        package = self.entity.package
        lookups = self.code_dictionary()
        return f"""
package {package}.{self.context["code_storage"]["root"]}.constants;

/**
 * 数据字典项
 *
 * @author {author}
 */
public enum DictionaryEnum {"{"}
{lookups}
{"}"}
"""

    def save_file(self, dir):
        _target_dir = os.path.join(dir, self.context["code_storage"]["root"], "constants")
        if not os.path.exists(_target_dir):
            os.makedirs(_target_dir)
        with open(
            os.path.join(_target_dir, "DictionaryEnum.java".format(self.entity.name)),
            mode="w",
            encoding="utf-8",
        ) as f:
            f.write(self.code())
